<template>
  <div class="teacher-page">
    <!-- 顶部标题区域 -->
    <div class="page-header mb-6">
      <h2 class="title">教师管理</h2>
      <p class="desc">管理所有教师信息及权限</p>
    </div>

    <!-- 搜索与操作区 -->
    <!-- <el-card class="search-card mb-6">
      <div class="search-container">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="搜索教师姓名"
                  prefix-icon="el-icon-search"
                  clearable
                ></el-input>
              </el-col>
              <el-col :span="4" style="min-width: 200px;">
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-card> -->

    <!-- 教师列表 -->
    <el-card>
      <div class="table-header" style="display: flex;">
        <el-button 
          type="primary" 
          icon="el-icon-plus"
          @click="openTeacherModal()"
          size="medium"
        >
          添加教师
        </el-button>
      </div>
      <el-table
        :data="teacherList"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <!-- 序号列 -->
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>

        <!-- 姓名列 -->
        <el-table-column
          label="姓名"
          min-width="120"
        >
          <template slot-scope="scope">
            <div class="user-info">
              <el-avatar :size="36" :src="scope.row.avatar">
                <i class="el-icon-user-solid"></i>
              </el-avatar>
              <span class="name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 电话列 -->
        <el-table-column
          prop="phone"
          label="手机号码"
          min-width="130"
        ></el-table-column>

        <!-- 角色列 -->
        <el-table-column
          label="角色"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.isAdmin ? 'danger' : 'primary'" size="small">
              {{ scope.row.isAdmin ? '管理员' : '教师' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 状态列 -->
        <el-table-column
          label="状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'" size="small">
              {{ scope.row.status === 'active' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          min-width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openTeacherModal(scope.row)"
            >
              编辑
            </el-button>
            <!-- <el-button
              type="text"
              size="small"
              :style="{ color: scope.row.status === 'active' ? '#F53F3F' : '#00B42A' }"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '停用' : '启用' }}
            </el-button> -->
            <el-button
              type="text"
              size="small"
              :style="{ color: scope.row.status === 'active' ? '#F53F3F' : '#00B42A' }"
              @click="handleDisable(scope.row)"
              v-if="!scope.row.isAdmin"
            >
              {{ scope.row.status === 'active' ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑教师抽屉 -->
    <el-drawer
      :title="modalTitle"
      :visible.sync="teacherModalVisible"
      direction="rtl"
      :size="600"
      :close-on-click-modal="false"
    >
      <div style="padding: 20px;">
        <el-form 
          :model="formData" 
          :rules="formRules" 
          ref="teacherForm" 
          label-width="100px"
          class="modal-form"
        >
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="头像">
                <div class="avatar-upload">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="uploadAvatar"
                    accept="image/*"
                  >
                    <img v-if="formData.avatar" :src="formData.avatar" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                  <div class="avatar-tips">支持JPG、PNG格式，大小不超过2MB</div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input 
                  v-model="formData.username" 
                  placeholder="请输入用户名(登录账号)"
                  :disabled="!!formData.id"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入手机号码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="角色" prop="isAdmin">
                <el-radio-group v-model="formData.isAdmin">
                  <el-radio :label="false">普通教师</el-radio>
                  <el-radio :label="true">管理员</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="账号状态" prop="status">
                <el-radio-group v-model="formData.status">
                  <el-radio label="active">正常</el-radio>
                  <el-radio label="disabled">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" >
              <el-form-item label="密码" prop="password">
                <el-input 
                  v-model="formData.password" 
                  placeholder="请输入密码"
                  show-password
                  type="password"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" >
              <el-form-item label="确认密码" prop="old_password">
                <el-input 
                  v-model="formData.old_password" 
                  placeholder="请再次输入密码"
                  show-password
                  type="password"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: right; margin-top: 30px;">
          <el-button @click="teacherModalVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTeacher">保存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'TeacherList',
  data() {
    // 确认密码验证
    const validateold_password = (rule, value, callback) => {
      if (!this.formData.id && value === '') {
        callback(new Error('请再次输入密码'));
      } else if (!this.formData.id && value !== this.formData.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      // 搜索表单
      searchForm: {
        keyword: '',
        department: '',
        status: ''
      },

      // 教师列表数据
      teacherList: [],

      // 分页配置
      pagination: {
        page: 1,
        size: 10,
        total: 4
      },

      // 对话框状态
      teacherModalVisible: false,
      modalTitle: '新增教师',

      // 表单数据
      formData: {
        id: '',
        name: '',
        username: '',
        phone: '',
        email: '',
        isAdmin: false,
        status: 'active',
        bio: '',
        password: '',
        old_password: ''
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 20, message: '用户名长度在4到20个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        password: [{
          required: true,
          validator: (rule, value, callback) => {
            if (!this.formData.id && !value) {
              callback(new Error('请输入密码'))
            } else if (value && (value.length < 6 || value.length > 20)) {
              callback(new Error('密码长度在6到20个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        old_password: [
          { validator: validateold_password, trigger: 'blur' }
        ]
      }
    };
  },

  mounted() {
    this.fetchTeacherList();
  },

  methods: {
    // 获取教师列表
    async fetchTeacherList() {
      try {
        const params = {
          page: this.pagination.page,
          page_size: this.pagination.size
        }
        
        const res = await api.admin.getAccountList(params)
        if (res.code === 200) {
          this.teacherList = (res.data || []).map(item => ({
            id: item.id,
            name: item.name || item.username,
            username: item.username,
            phone: item.phone || '',
            email: item.email || '',
            avatar: item.avatar || '',
            isAdmin: item.is_admin === 1 || item.is_admin === true,
            status: item.status === 1 || item.status === true ? 'active' : 'disabled',
            bio: item.bio || '',
            created_at: item.created_at
          }))
          
          this.pagination.total = res.pagination?.total || this.teacherList.length
        }
      } catch (error) {
        this.$message.error('获取教师列表失败')
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1;
      this.fetchTeacherList();
      this.$message.success('搜索功能已触发');
    },

    // 重置
    handleReset() {
      this.searchForm = {
        keyword: '',
        department: '',
        status: ''
      };
      this.pagination.page = 1;
      this.fetchTeacherList();
      this.$message.success('已重置搜索条件');
    },

    // 打开新增/编辑抽屉
    openTeacherModal(teacher) {
      if (teacher) {
        // 编辑
        this.modalTitle = '编辑教师';
        // 处理头像：如果是URL则去掉时间戳参数，如果是base64则直接使用
        const avatar = teacher.avatar || '';
        let cleanAvatar = avatar;
        if (avatar && !avatar.startsWith('data:image/')) {
          // URL格式，去掉时间戳参数
          cleanAvatar = avatar.split('?')[0];
        }
        this.formData = { 
          ...teacher, 
          avatar: cleanAvatar,
          password: '', 
          old_password: '' 
        };
      } else {
        // 新增
        this.modalTitle = '新增教师';
        this.formData = {
          id: '',
          name: '',
          username: '',
          phone: '',
          email: '',
          avatar: '',
          isAdmin: false,
          status: 'active',
          bio: '',
          password: '',
          old_password: ''
        };
      }
      this.teacherModalVisible = true;
      this.$nextTick(() => {
        this.$refs.teacherForm && this.$refs.teacherForm.clearValidate();
      });
    },

    // 保存教师
    saveTeacher() {
      this.$refs.teacherForm.validate(async valid => {
        if (!valid) return;
        
        const isEdit = !!this.formData.id;
        
        try {
          // 准备提交数据
          const submitData = {
            username: this.formData.username,
            name: this.formData.name,
            phone: this.formData.phone,
            is_admin: this.formData.isAdmin ? 1 : 0,
            status: this.formData.status === 'active' ? 1 : 0
          };

          // 添加可选字段
          if (this.formData.email) submitData.email = this.formData.email;
          if (this.formData.bio) submitData.bio = this.formData.bio;
          // 处理头像：如果是base64格式直接提交，如果是URL则去掉时间戳参数
          if (this.formData.avatar) {
            if (this.formData.avatar.startsWith('data:image/')) {
              // base64格式，直接提交
              submitData.avatar = this.formData.avatar;
            } else {
              // URL格式，去掉时间戳参数
              const cleanAvatar = this.formData.avatar.split('?')[0];
              submitData.avatar = cleanAvatar;
            }
          }

          // 编辑或新增处理
          if (isEdit) {
            submitData.id = this.formData.id;
            // 如果填写了新密码才提交
            if (this.formData.password) {
              submitData.password = this.formData.password;
              submitData.old_password = this.formData.old_password;
            }
            await api.admin.updateAccount(submitData);
            this.$message.success('教师信息更新成功');
          } else {
            // 新增时密码必填
            submitData.password = this.formData.password;
            submitData.old_password = this.formData.old_password;
            await api.admin.createAccount(submitData);
            this.$message.success('教师添加成功');
          }
          
          this.teacherModalVisible = false;
          await this.fetchTeacherList();
        } catch (error) {
          this.$message.error(error.message || '保存失败,请稍后重试');
        }
      });
    },

    // 切换状态
    async toggleStatus(teacher) {
      const newStatus = teacher.status === 'active' ? 'disabled' : 'active';
      const action = newStatus === 'active' ? '启用' : '停用';
      
      try {
        await this.$confirm(`确定要${action}教师 ${teacher.name} 吗？`, '提示', {
          type: 'warning'
        });
        
        // 调用API更新状态
        await api.admin.updateAccount({
          id: teacher.id,
          status: newStatus === 'active' ? 1 : 0
        });
        
        // 更新本地状态
        teacher.status = newStatus;
        this.$message.success(`${action}成功`);
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '操作失败，请稍后重试');
        }
      }
    },

    // 停用教师
    async handleDisable(teacher) {
      if (teacher.isAdmin) {
        this.$message.warning('管理员账号不能停用');
        return;
      }

      let updateStatusName = teacher.status === 'active' ? '停用' : '启用';

      try {
        await this.$confirm(`确定要${updateStatusName}教师 ${teacher.name} 吗？`, '提示', {
          type: 'warning'
        });
        
        await api.admin.updateAccount({...teacher, ...{status: teacher.status === 'active' ? 0 : 1}});
        
        this.$message.success(`${updateStatusName}成功`);
        
        // 刷新列表
        await this.fetchTeacherList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || `${updateStatusName}失败，请稍后重试`);
        }
      }
    },

    // 头像上传前验证
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },

    // 自定义头像上传（转换为base64格式）
    uploadAvatar(params) {
      const file = params.file;
      const reader = new FileReader();
      
      reader.onload = (e) => {
        // 将文件转换为base64格式
        const base64 = e.target.result;
        // 存储base64数据到formData中
        this.formData.avatar = base64;
        this.$message.success('头像已选择，保存时将一起提交');
      };
      
      reader.onerror = () => {
        this.$message.error('头像读取失败，请重试');
      };
      
      // 读取文件为base64
      reader.readAsDataURL(file);
    },

    // 分页
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.page = 1;
      this.fetchTeacherList();
    },

    handleCurrentChange(page) {
      this.pagination.page = page;
      this.fetchTeacherList();
    }
  }
};
</script>

<style scoped>
/* 页面标题 */
.page-header {
  margin-bottom: 20px;
  text-align: left;
}
.title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin-bottom: 5px;
}
.desc {
  color: #86909C;
  font-size: 14px;
}

/* 搜索区 */
.search-card {
  padding: 15px 20px;
}
.search-container {
  width: 100%;
}

/* 表格头部操作栏 */
.table-header {
  margin-bottom: 16px;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info .name {
  font-weight: 500;
  color: #304156;
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 抽屉表单样式 */
.modal-form {
  padding-right: 20px;
}

.modal-form .el-select {
  width: 100%;
}

/* 头像上传样式 */
.avatar-upload {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  display: block;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.avatar-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  padding-top: 10px;
}
</style>
